package com.spider.admin.scaffold.common;

import com.spider.admin.scaffold.exception.BusinessException;
import com.spider.admin.scaffold.exception.ExceptionDef;
import com.spider.admin.scaffold.service.TokenBlacklistService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2020/10/31 19:02
 */
@Slf4j
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {


  @Autowired
  private TokenBlacklistService tokenBlacklistService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    // 排除不需要拦截的路径
    if (isExcludePath(request)) {
      return true;
    }

    // 从请求头获取token
    String token = extractToken(request);
    if (StringUtils.isEmpty(token)) {
      throw new BusinessException("缺少访问令牌");
    }

    // 验证token
    if (tokenBlacklistService.isBlacklisted(token)) {
      throw new BusinessException(ExceptionDef.ERROR_USER_TOKEN_INVALID);
    }

    return true;
  }

  // 从请求中提取令牌
  private String extractToken(HttpServletRequest request) {
    String bearerToken = request.getHeader("Authorization");
    if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
      return bearerToken.substring(7);
    }
    return null;
  }


  private boolean isExcludePath(HttpServletRequest request) {
    // 实现你的排除路径逻辑，比如登录、注册等接口
    String path = request.getServletPath();
    return path.startsWith("/swagger") ||
        path.startsWith("/v3/api-docs");
  }
}
